package com.sdau.repairmaster.UIFile;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.sdau.repairmaster.R;
import com.sdau.repairmaster.logic.tools.UserUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import FunctionalModule.PasswordStrength;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ResetPwdActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private PasswordStrength passwordStrength;//密码检测类
    private EditText etResetPwd;//新密码
    private EditText reeditTextPwd;//确认新密码
    private Button btnResetSubmit;//确认按钮
    private ImageButton ibtnBack;//引入布局中的返回按钮

    private final int FAILURE_CODE=1001;//失败
    private final int SUCCESS_CODE=1000;//成功

    //记录账号
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    /*
           看数据库中是否存在该账户以及密码是否正确
        */
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE://成功
                    String data= (String) msg.obj;
                    Log.d("MIN",data);
                    if("true".equals(data.trim()))
                        updateSuccess();
                    else
                        updateFaile();
                    break;
                case FAILURE_CODE://失败
                    Toast.makeText(ResetPwdActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_reset_pwd);

        initView();//初始化组件
        registerListener();//注册监听器
    }
    public void initView(){
        etResetPwd = findViewById(R.id.et_reset_pwd);//获取新密码
        reeditTextPwd=findViewById(R.id.re_et_reset_pwd);//获取确认密码
        btnResetSubmit = findViewById(R.id.bt_reset_submit);//获取确认按钮
        ibtnBack = findViewById(R.id.ib_navigation_back);//获取按钮
    }

    /**
     * 注册监听器
     */
    public void registerListener(){

        btnResetSubmit.setOnClickListener(ResetPwdActivity.this);
        ibtnBack.setOnClickListener(ResetPwdActivity.this);

        etResetPwd.addTextChangedListener(ResetPwdActivity.this);
    }
    /**
     * 实现监听器
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ib_navigation_back:
                finish();
                break;
            case R.id.bt_reset_submit:
                resetRequest();
                break;

        }
    }



    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String newPwd = etResetPwd.getText().toString().trim();
        if(newPwd.length()>= 6 && newPwd.length()<=8){
            btnResetSubmit.setBackgroundResource(R.drawable.bg_login_submit);
            btnResetSubmit.setTextColor(getResources().getColor(R.color.white));
        }else{
            btnResetSubmit.setBackgroundResource(R.drawable.bg_login_submit_lock);
            btnResetSubmit.setTextColor(getResources().getColor(R.color.login_input_active));
        }
    }



    //重置密码
    //与服务器交互
    public void resetRequest(){

        String reset_pwd = etResetPwd.getText().toString().trim();
        String re_reset_pwd = reeditTextPwd.getText().toString().trim();
        if(!reset_pwd.equals(re_reset_pwd)){
            Toast.makeText(ResetPwdActivity.this, "两次密码输入不一致",
                    Toast.LENGTH_SHORT).show();
        }
        else if(!UserUtils.checkPwd(reset_pwd)){
            Toast.makeText(ResetPwdActivity.this, "格式错误",
                    Toast.LENGTH_SHORT).show();
        }
        else if(UserUtils.checkPwd(reset_pwd)){
            updatePwd(reset_pwd);
        }

        /*
        if(!etResetPwd.getText().toString().equals(reeditTextPwd.getText().toString()))
            Toast.makeText(ResetPwdActivity.this, "两次密码输入不一致", Toast.LENGTH_SHORT).show();
        else {
            passwordStrength=new PasswordStrength(etResetPwd.getText().toString());
            if(passwordStrength.Score()>=60)
            {

                startActivity(new Intent(ResetPwdActivity.this,HomeActivity.class));//跳转入主页面
                //重设密码，写入数据库
                finish();//销毁页面，防止用户返回至此
            }
            else
            {
                Toast.makeText(ResetPwdActivity.this, "密码过于简单，请重新设置", Toast.LENGTH_SHORT).show();
            }

        }

         */

    }
    /*
    具体更新密码的逻辑
     */

    public void updatePwd(String pwd){

        final String URL_login = "http://39.99.174.38/RepairAdmin/userServlet";
        final Message message=Message.obtain();

        String phone = getIntent().getStringExtra("phone");

        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();



        RequestBody requestBody = new FormBody.Builder()
                .add("phone", phone)
                .add("pwd",pwd)
                .add("flag","updatePwdByPhone")
                .build();


        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(URL_login)
                .post(requestBody)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what=FAILURE_CODE;
                message.obj=e.getMessage();//失败的信息
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data=response.body().string();
                message.what=SUCCESS_CODE;
                message.obj=data;
                handler.sendMessage(message);

            }
        });
    }

    public void updateSuccess(){



        startActivity(new Intent(ResetPwdActivity.this,HomeActivity.class));//跳转入主页面
        finish();//销毁页面，防止用户返回至此
    }

    public void updateFaile(){
        Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(ResetPwdActivity.this,LoginActivity.class));//跳转入主页面
    }
}